package ext;

import org.junit.*;

public class AddOf36 {
    /**
     * 1b + 2x = 48
     */
    public String add(String a, String b) {
        int m, n;
        if ((m = a.length()) > (n = b.length()))
             return add(b, a);
        StringBuilder sb = new StringBuilder();
        char[] as = a.toCharArray(), bs = b.toCharArray();
        int flag = 0;
        for (int i = 0; i < m; i++) {
            int ac = parse(as[m - i - 1]);
            int bc = parse(bs[n - i - 1]);
            int sum = ac + bc + flag;
            flag = sum / 36;
            sum %= 36;
            if (sum < 10) {
                sb.insert(0, sum);
            } else {
                sb.insert(0, (char)(sum - 10 + 'a'));
            }
        }
        for (int i = m; i < n; i++) {
            int bc = parse(bs[n - i - 1]);
            int sum = bc + flag;
            flag = sum / 36;
            sum %= 36;
            if (sum < 10) {
                sb.insert(0, sum);
            } else {
                sb.insert(0, (char)(sum - 10 + 'a'));
            }
        }
        if (flag == 1) {
            sb.insert(0, 1);
        }
        return sb.toString();
    }

    public int parse(char c) {
        if (c >= '0' && c <= '9') {
            return c - '0';
        } else {
            return c - 'a' + 10;
        }
    }

    @Test
    public void test() {
        System.out.println(add("1b", "2x"));
        System.out.println(add("zz", "zz"));

    }
}
